package com.kzd.btgame.main.game

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ConvertUtils
import com.kzd.btgame.R
import com.kzd.btgame.custom.setOnClickAntiShakeListener
import com.kzd.btgame.custom.setTransitionStatus
import com.kzd.btgame.custom.setTransitionStatusE
import com.kzd.btgame.databinding.ActivityDiscussReplyBinding
import com.kzd.btgame.entity.GameDiscuss
import com.kzd.btgame.jetpack.vm.GameViewModel
import com.kzd.btgame.main.KEY_GAME_DETAILS_DISCUSS
import com.kzd.btgame.main.KEY_GAME_DETAILS_ID
import com.kzd.btgame.main.KEY_GAME_DETAILS_TITLE
import com.kzd.btgame.main.game.adapter.GameDiscussImageAdapter
import com.kzd.btgame.main.game.adapter.GameDiscussReplyAdapter
import com.kzd.btgame.main.popup.CouponReplyPopup
import com.module.lemlin.app.OwnerStatusBar
import com.module.lemlin.http.Status
import com.module.lemlin.image.loadCircleImage
import com.module.lemlin.image.loadImage
import com.module.lemlin.owner.OwnerViewBindingActivity
import com.module.lemlin.owner.ownerViewModel
import java.lang.StringBuilder

class DiscussReplyActivity : OwnerViewBindingActivity<ActivityDiscussReplyBinding>() {

    private val mCouponReplyPopup: CouponReplyPopup by lazy {
        CouponReplyPopup(this) { _, content ->
            mGameDiscuss?.let {
                mViewMode.userDiscussIssue(
                    id = mGameId, content = content, reply_uid = it.uid, pid = it.id
                )
            }
        }
    }

    private val mGameDiscussReplyAdapter = GameDiscussReplyAdapter()

    private val mTitle: String
        get() = intent?.extras?.getString(KEY_GAME_DETAILS_TITLE) ?: ""

    private val mGameId: String
        get() = intent?.extras?.getString(KEY_GAME_DETAILS_ID) ?: ""

    private val mGameDiscuss: GameDiscuss? by lazy {
        intent?.extras?.getSerializable(KEY_GAME_DETAILS_DISCUSS) as? GameDiscuss
    }


    private val mViewMode: GameViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater) -> ActivityDiscussReplyBinding
        get() = ActivityDiscussReplyBinding::inflate

    override fun initStatusBar(statusBar: OwnerStatusBar) {
        statusBar.run {
            addView = mViewBinding.flDiscussReplyBar
            barColor = R.color.white
        }
        super.initStatusBar(statusBar)
    }

    override fun initView() {

        mViewBinding.flDiscussReplyBar.setTitleTextContent(mTitle)

        mViewBinding.includeDiscussReplyBody.rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = mGameDiscussReplyAdapter.apply {
            mGameDiscuss?.let {
                val view = createHeaderView(
                    context = this@DiscussReplyActivity, gameDiscuss = it
                )
                mGameDiscussReplyAdapter.setHeaderView(view)
            }
        }

        mViewBinding.includeDiscussReplyBody.mSmartRefreshLayout.setOnRefreshListener {
            mGameDiscuss?.let { discuss ->
                mViewMode.gameDiscussReply(discuss.id)
            }
        }
        mViewBinding.includeDiscussReplyBody.mSmartRefreshLayout.setOnLoadMoreListener {
            mGameDiscuss?.let { discuss ->
                mViewMode.gameDiscussReply(discuss.id, isLoadMore = true)
            }
        }

        mViewBinding.tvDiscussReplyLike.setOnClickAntiShakeListener {
            mGameDiscuss?.let {
                mViewMode.gameDiscussGreat(it.id, it.is_zan)
            }
        }

        mViewBinding.tvDiscussReplyContent.setOnClickAntiShakeListener {
            mCouponReplyPopup.fillData().showPopupWindow()
        }
    }

    override fun initData() {
        mGameDiscuss?.let {
            fillData(it)
        }
        mGameDiscuss?.let {
            mViewMode.gameDiscussReply(it.id)
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun fillData(gameDiscuss: GameDiscuss) {
        mViewBinding.tvDiscussReplyLike.text = gameDiscuss.zan
        val left = resources.getDrawable(
            if (gameDiscuss.is_zan == 1) R.drawable.ic_10004 else R.drawable.ic_10003, null
        )
        left.setBounds(0, 0, left.minimumWidth, left.minimumHeight)
        mViewBinding.tvDiscussReplyLike.setCompoundDrawables(left, null, null, null)
    }

    override fun initViewMode() {

        mViewMode.discussChildLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatusE(response, mGameDiscussReplyAdapter, mViewBinding.includeDiscussReplyBody.mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            if (isLoadMore) {
                mGameDiscussReplyAdapter.addData(data)
            } else {
                mGameDiscussReplyAdapter.setNewInstance(data)
            }
        })

        mViewMode.discussGreatLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data
                ?: return@observe
            mGameDiscuss?.apply {
                this.is_zan = data.isGreat
                this.zan = if (data.isGreat == 1)
                    (zan.toInt() + 1).toString()
                else (zan.toInt() - 1).toString()
            }?.let { fillData(it) }
        })

        mViewMode.userDiscussIssueLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            mCouponReplyPopup.dismiss()
            mGameDiscuss?.let {
                mViewMode.gameDiscussReply(it.id)
            }
        })
    }


    private fun createHeaderView(
        context: Context, gameDiscuss: GameDiscuss,
    ): View = LayoutInflater.from(context).inflate(R.layout.view_discuss_reply_heads, (null))
        .apply {
            findViewById<TextView>(R.id.tvDiscussReplyUserName)
                .text = gameDiscuss.user_name
            findViewById<TextView>(R.id.tvDiscussReplyContent)
                .text = gameDiscuss.content
            findViewById<TextView>(R.id.tvDiscussReplyTime)
                .text = gameDiscuss.time
            findViewById<TextView>(R.id.tvDiscussReplyNumber)
                .text = StringBuilder().append("（").append(gameDiscuss.pinglun).append("）")
            findViewById<ImageView>(R.id.ivDiscussReplyUserHead)
                .loadCircleImage(gameDiscuss.face)
            findViewById<ImageView>(R.id.ivDiscussReplyUserGarde)
                .loadImage(gameDiscuss.huiyuan_img)

            val mDiscussImageAdapter = GameDiscussImageAdapter()
            findViewById<RecyclerView>(R.id.rvDiscussReplyImageBody).apply {
                layoutManager = GridLayoutManager(context, 3)
                addItemDecoration(ItemDecoration())
            }.adapter = mDiscussImageAdapter
            val imageStr = gameDiscuss.image
            if (imageStr.isNullOrEmpty()) {
                mDiscussImageAdapter.setNewInstance(mutableListOf())
            } else {
                mDiscussImageAdapter.setNewInstance(imageStr.split(",").toMutableList())
            }
        }

    inner class ItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State,
        ) {
            val position: Int = parent.getChildAdapterPosition(view)
            if (position == 0) {
                outRect.left = ConvertUtils.dp2px(0f)
            }
            if (position == state.itemCount - 1) {
                outRect.right = ConvertUtils.dp2px(0f)
            } else {
                outRect.right = ConvertUtils.dp2px(5f)
            }
            outRect.top = ConvertUtils.dp2px(5f)
            outRect.bottom = ConvertUtils.dp2px(5f)
        }
    }
}